package blue.qingyu.whimurmur.enhancement.directive;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

import io.jboot.utils.StrUtil;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jpress.module.article.model.Article;
import io.jpress.module.article.service.ArticleService;

@JFinalDirective("thumbUpEx")
public class ThumbUpExDirective extends JbootDirectiveBase {
	
	@com.jfinal.aop.Inject
    private ArticleService service;

	@Override
	public void onRender(Env env, Scope scope, Writer writer) {
		String idOrSlug = getPara(0, scope);
        Article article = getArticle(idOrSlug);
        if (article == null) {
        	scope.setLocal("thumbUpNum", 0);
            return;
        }
		Long articleId = article.getId();
        Long thumbUpNum = Db.queryLong("select thumb_up_num from ex_thumb_up where article_id = ? ", articleId);
        scope.setLocal("thumbUpNum", thumbUpNum == null ? 0l : thumbUpNum);
//        System.out.println("thumbUpNum:"+thumbUpNum+",idOrSlug"+idOrSlug);
        renderBody(env, scope, writer);
	}
	
	@Override
    public boolean hasEnd() {
        return true;
    }
	
	private Article getArticle(String idOrSlug) {
        return StrUtil.isNumeric(idOrSlug)
                ? service.findById(idOrSlug)
                : service.findFirstBySlug(idOrSlug);
    }
}
